package com.zd.application.web.listener;

import java.util.Date;
import java.util.Hashtable;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.zd.application.common.Constant;
import com.zd.application.service.ManageUtil;
import com.zd.application.service.UserHandler;

public class ServerListener implements ServletContextListener, HttpSessionListener {

	@Override
	public void contextInitialized(ServletContextEvent event) {
		Hashtable<String, UserHandler> userHandlers = new Hashtable<String, UserHandler>();
		ServletContext context = event.getServletContext();
		context.setAttribute("userHandlers", userHandlers);
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {}

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		//设置Session过期时间
		event.getSession().setMaxInactiveInterval(Constant.SESSION_LOST);
		System.out.println(event.getSession().getId() + " created " + new Date());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		UserHandler userHandler = (UserHandler) session.getAttribute("userHandler");
		if(userHandler != null) {
			ServletContext app = session.getServletContext();
			Hashtable<String, UserHandler> userHandlers =  (Hashtable<String, UserHandler>) app.getAttribute("userHandlers");
			ManageUtil.kick(userHandler, userHandlers);
		}
		System.out.println(session.getId() + " destoryed " + new Date());
	}

}
